
package com.syz.fs.file;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericProgressiveFutureListener;
import io.netty.util.concurrent.ProgressiveFuture;

/**
 *  基于 LineBasedFrameDecoder 和 StringDecoder 完成的 按行 文本编解码。。解决拆包和分包问题
 *  
 *  
 * @author SYZ
 * @date 2017年11月22日 下午1:07:39
 * @version 1.0.0
 * @see com.syz.FileClient.frame.correct.TimeClient
 */
public class FileClient {

	private ChannelFuture f ;
	public void connect(int port, String host) throws Exception {
		// 配置客户端NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch)
								throws Exception {
							ch.pipeline().addLast(
									new LineBasedFrameDecoder(1024));//用于按行 分包 
							ch.pipeline().addLast(new StringDecoder());
							ch.pipeline().addLast(new FileClientHandler());
						}
					});

			// 发起异步连接操作
			f = b.connect(host, port).sync();

			send("D:\\project\\get-Next\\Net-Server-MQ\\vertx\\pom.xml");
			// 当代客户端链路关闭
			f.channel().closeFuture().sync();
		} finally {
			// 优雅退出，释放NIO线程组
			group.shutdownGracefully();
		}
	}

	
	public void send(String path) throws InterruptedException{
		byte[] req = (path+System.getProperty("line.separator"))
				.getBytes();
		ByteBuf message = Unpooled.buffer(req.length);
		message.writeBytes(req);
		ChannelFuture cf = f.channel().writeAndFlush(message).syncUninterruptibly();
		
		//后续为  listener的测试，，正式场景 一般不需要监控，，另外 由于是异步，也很难 写同步方法，，例如同步获取返回消息；【后续需要关注是否有现有实现】
		cf.addListener(new GenericProgressiveFutureListener(){

			@Override
			public void operationProgressed(ProgressiveFuture future,
					long progress, long total) throws Exception {
				
				System.out.println("write operationProgressed ------- tow");
				// TODO Auto-generated method stub
				if (total < 0) { // total unknown
					System.err.println("Transfer progress: " + progress);
				} else {
					System.err.println("Transfer progress: " + progress + " / "
							+ total);
				}
			}

			@Override
			public void operationComplete(Future future)
					throws Exception {
				// TODO Auto-generated method stub
				System.out.println("write ok ------- tow");
			}

		});
		
		
		cf.addListener(new ChannelFutureListener(){

			@Override
			public void operationComplete(ChannelFuture future)
					throws Exception {
				System.out.println("write ok");
				System.out.println(future.getNow());
				System.out.println(future.get());
				System.out.println(future.isSuccess());
				System.out.println(future.isDone());
				System.out.println(future.isCancelled());
				
//				future.channel().read().alloc();
				ByteBuf buf = (ByteBuf) future.channel().read().alloc().buffer();//读取不到数据。，可能是异步，也可能是 channelFutrue  只是对应的 wirte这个
				byte[] req = new byte[buf.readableBytes()];
				buf.readBytes(req);
				String body = new String(req, "UTF-8");
				
				
	
				
				System.out.println(body+"\n\n\n\n\n--------------------future.channel().alloc().buffer()");
				System.out.println(future.cancel(true)); //已经完成，，false，，看了 future 是跟 具体时间绑定 例如是 write connect
				System.out.println(future.isCancelled());
				
			}});
	}
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if (args != null && args.length > 0) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (NumberFormatException e) {
				// 采用默认值
			}
		}
		new FileClient().connect(port, "127.0.0.1");
	}
}
